/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.templateproject.activity;

import static com.xuexiang.xutil.XUtil.runOnUiThread;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xuexiang.templateproject.R;
import com.xuexiang.templateproject.bean.Question;
import com.xuexiang.templateproject.bean.QuestionBean;
import com.xuexiang.templateproject.bean.QuestionForDLS;
import com.xuexiang.templateproject.core.BaseActivity;
import com.xuexiang.templateproject.core.BaseFragment;
import com.xuexiang.templateproject.databinding.ActivityMainBinding;
import com.xuexiang.templateproject.databinding.ActivityMatchBinding;
import com.xuexiang.templateproject.fragment.camera.CameraFragment;
import com.xuexiang.templateproject.fragment.home.HomeFragment;
import com.xuexiang.templateproject.fragment.other.AboutFragment;
import com.xuexiang.templateproject.fragment.other.SettingsFragment;
import com.xuexiang.templateproject.utils.DbUtils;
import com.xuexiang.templateproject.utils.sdkinit.XUpdateInit;
import com.xuexiang.templateproject.widget.GuideTipsDialog;
import com.xuexiang.templateproject.widget.showLoadingDialog;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.adapter.FragmentAdapter;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.app.ActivityUtils;
import com.xuexiang.xutil.common.ClickUtils;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.common.logger.Logger;
import com.xuexiang.xutil.display.ImageUtils;

import java.util.List;

/**
 * 程序主页面,只是一个简单的Tab例子
 *
 * @author xuexiang
 * @since 2019-07-07 23:53
 */
public class MatchActivity extends BaseActivity<ActivityMatchBinding> implements View.OnClickListener{

    private static int REQUEST_CODE =10;
    private List<Question> questionlist;
    @AutoWired(name = CameraViewActivity.KEY_PICTURE_PATH)
    String mImgPath;
    /**
     * 是拍摄的图片
     */
    @AutoWired(name = "data")
    String mData;
    @Override
    protected ActivityMatchBinding viewBindingInflate(LayoutInflater inflater) {
        return ActivityMatchBinding.inflate(inflater);
    }
    public static void open(@NonNull Activity activity, String imgPath, String data) {
        Intent intent = new Intent(activity, MatchActivity.class);
        intent.putExtra("data", data);
        intent.putExtra(CameraViewActivity.KEY_PICTURE_PATH, imgPath);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XRouter.getInstance().inject(this);
        if (StringUtils.isEmpty(mImgPath)) {
            finish();
            return;
        }
        initViews();

    }
    @Override
    protected boolean isSupportSlideBack() {
        return true;
    }

    private void initViews() {
        Logger.d("MatchActivity "+mImgPath+" "+mData);
        binding.save.setOnClickListener(this);
        binding.print.setOnClickListener(this);
        WebSettings webSettings = binding.webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        this.binding.webView.setVerticalScrollbarOverlay(true);
//        this.binding.webView.loadUrl("file:///android_asset/index.html");
//        binding.webView.loadUrl("javascript:addBody('"+mData+"')");
       questionlist = new Gson().fromJson(mData, new TypeToken<List<Question>>(){}.getType());
        String content = "";
        for(int i=0;i<questionlist.size();i++){
            Question questionContent = questionlist.get(i);
                    if(questionContent!=null){
                        Logger.i(questionContent.getQuestionType());
                        Logger.i(questionContent.getQuestionAndOption());
                        Logger.i(questionContent.getAnswerAndAnalyze());
                        content=content+questionContent.getQuestionType()+"\n[题干]\n";
                        content=content+questionContent.getQuestionAndOption()+"\n";
                        content=content+"[答案和分析]\n";
                        content=content+questionContent.getAnswerAndAnalyze()+"\n";
                        if(i>1) break;
                    }
                }
        binding.webView.setText(content);
    }


    @SingleClick
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.nav_header) {
            XToastUtils.toast("点击头部！");
        }else if(id == R.id.save){
            for(int i=0;i<questionlist.size();i++){
                Question questionContent = questionlist.get(i);
                if(questionContent!=null){
                    if(DbUtils.getInstance().getQuestionByQuestionId(questionContent.getQuestionId())==null){
                        QuestionBean questionBean = new QuestionBean();
                        questionBean.setQuestionId(questionContent.getQuestionId());
                        questionBean.setQuestionType(questionContent.getQuestionType());
                        questionBean.setQuestionAndOption(questionContent.getQuestionAndOption());
                        questionBean.setAnswerAndAnalyze(questionContent.getAnswerAndAnalyze());
                        questionBean.setUpdateTime(System.currentTimeMillis());
                        DbUtils.getInstance().insertOrReplaceQuestion(questionBean);
                    }
                }
            }
            XToastUtils.toast("保存成功！");
            binding.save.setEnabled(false);
        }else if(id == R.id.print){
            showLoadingDialog.showLoading(this);;
            new Thread("io") {
                @Override
                public void run() {
                    String imgpath = getCacheDir()+"print_"+System.currentTimeMillis()+".png";
                    ImageUtils.save(binding.webView,imgpath, Bitmap.CompressFormat.PNG);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingDialog.hideLoading();
                            binding.print.setEnabled(true);
                            ActivityUtils.startActivity(SearchBTActivity.class,"imgPath",imgpath);
                        }
                    });
                }}.start();
            binding.print.setEnabled(false);
        }
    }


}
